package com.wjl.picture.common.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;

/**
 * Description: 配置所有拦截器
 * Date: 2023-04-05
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截器
        registry.addInterceptor(new SaInterceptor(handler->{
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {
                                SaHolder.getResponse().setStatus(HttpServletResponse.SC_OK);
                                SaHolder.getResponse().setHeader("Access-Control-Allow-Credentials", "true");
                                SaHolder.getResponse().setHeader("Access-Control-Allow-Origin", "http://localhost:8000");
                                SaHolder.getResponse().setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                                SaHolder.getResponse().setHeader("Access-Control-Max-Age", "3600");
                                SaHolder.getResponse().setHeader("Access-Control-Allow-Headers", "authorization, content-type");
                            })
                            .back();
                    SaRouter.match("/**").check(r-> StpUtil.checkLogin());

                }))
                // 设置需要拦截的路径
                .addPathPatterns("/**")
                // 设置不需要拦截的路径
                .excludePathPatterns(
                        "/user/login",
                        "/user/register",
                        "/user/callback",
                        "/wx/**",
                        "/wx/index",
                        "/doc.html", // Knife4J 文档页面
                        "/swagger-resources/**", // Knife4J API 资源
                        "/webjars/**", // Knife4J UI 资源
                        "/v2/api-docs", // Swagger JSON
                        "/v3/api-docs", // OpenAPI JSON
                        "/issue/license"//  Issue
                );
    }
}
